#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Last Update:

'''docstring
'''

__revision__ = '0.1'
__author__ = 'lxd'

import sys
sys.path.append('.')
sys.path.append('..')
import wx
import os
import Image
import tools

class MainFrame(wx.Frame):
    def __init__(self,log,path):
        wx.Frame.__init__(self, None, -1, u'图像分析', size=(600, 400))
        self.log = log
        self.path = path
        self.lblFiles = wx.StaticText(self,-1,u'截屏文件列表')
        self.lstFiles = wx.ListBox(self,-1,style = wx.LB_EXTENDED,size = (-1,200))
        self.Bind(wx.EVT_LISTBOX, self.OnItemClick, self.lstFiles) 

        self.lblYes = wx.StaticText(self,-1,u'有——列表')
        self.lstYes = wx.ListBox(self,-1,style = wx.LB_EXTENDED,size = (-1,200))
        self.btnAddYes = wx.Button(self,-1,u'添加')
        self.btnDelYes = wx.Button(self,-1,u'删除')
        self.btnReload = wx.Button(self,-1,u'重新载入')
        self.Bind(wx.EVT_BUTTON, self.OnAddYesClick, self.btnAddYes)
        self.Bind(wx.EVT_BUTTON, self.OnDelYesClick, self.btnDelYes)
        self.Bind(wx.EVT_LISTBOX, self.OnItemClick, self.lstYes) 
        self.Bind(wx.EVT_BUTTON, self.OnReloadClick, self.btnReload)

        self.lblNo = wx.StaticText(self,-1,u'没有——列表')
        self.lstNo = wx.ListBox(self,-1,style = wx.LB_EXTENDED,size = (-1,200))
        self.btnAddNo = wx.Button(self,-1,u'添加')
        self.btnDelNo = wx.Button(self,-1,u'删除')
        self.Bind(wx.EVT_BUTTON, self.OnAddNoClick, self.btnAddNo)
        self.Bind(wx.EVT_BUTTON, self.OnDelNoClick, self.btnDelNo)
        self.Bind(wx.EVT_LISTBOX, self.OnItemClick, self.lstNo) 
        
        self.lblPoint = wx.StaticText(self,-1,u'输入')
        self.lblPointX0 = wx.StaticText(self,-1,u'起点x')
        self.txtPointX0 = wx.TextCtrl(self,-1,'0')
        self.lblPointY0 = wx.StaticText(self,-1,u'起点y')
        self.txtPointY0 = wx.TextCtrl(self,-1,'0')

        self.lblPointX = wx.StaticText(self,-1,u'x')
        self.txtPointX = wx.TextCtrl(self,-1)
        self.lblPointY = wx.StaticText(self,-1,u'y')
        self.txtPointY = wx.TextCtrl(self,-1)
        self.lblPointColor = wx.StaticText(self,-1,u'color')
        self.txtPointColor = wx.TextCtrl(self,-1)
        self.btnAnalyse= wx.Button(self,-1,u'分析')
        self.Bind(wx.EVT_BUTTON, self.OnAnalyseClick, self.btnAnalyse)

        self.lblCase1 = wx.StaticText(self,-1,u'坐标 -> 颜色')
        self.lblCase1Point = wx.StaticText(self,-1,u'坐标(x,y)')
        self.txtCase1Point = wx.TextCtrl(self,-1)
        self.btnCase1= wx.Button(self,-1,u'分析')
        self.lblCase1Result= wx.StaticText(self,-1,u'颜色')
        self.txtCase1Result = wx.TextCtrl(self,-1)
        self.Bind(wx.EVT_BUTTON, self.OnCase1Click, self.btnCase1)

        self.lblCase2 = wx.StaticText(self,-1,u'范围中的颜色 -> 坐标')
        self.lblCase2Point = wx.StaticText(self,-1,u'范围坐标(x0,y0,x1,y1)')
        self.txtCase2Point = wx.TextCtrl(self,-1)
        self.lblCase2Color= wx.StaticText(self,-1,u'颜色')
        self.txtCase2Color= wx.TextCtrl(self,-1)
        self.btnCase2= wx.Button(self,-1,u'分析')
        self.lblCase2Result= wx.StaticText(self,-1,u'坐标')
        self.txtCase2Result = wx.TextCtrl(self,-1)
        self.Bind(wx.EVT_BUTTON, self.OnCase2Click, self.btnCase2)

        self.lblImg = wx.StaticText(self,-1,u'图像预览')
        self.sw = wx.ScrolledWindow(self)
        self.img = wx.StaticBitmap(self.sw,-1,size = (800,600))
        self.sw.SetScrollbars(20, 20,64,40)

        self.layout()
        self.init()

    def layout(self):
        btnYesSizer = wx.BoxSizer(wx.VERTICAL)
        btnYesSizer.Add(self.btnAddYes,0,wx.ALL,5)
        btnYesSizer.Add(self.btnDelYes,0,wx.ALL,5)
        btnYesSizer.Add(self.btnReload,0,wx.ALL,5)
        
        btnNoSizer = wx.BoxSizer(wx.VERTICAL)
        btnNoSizer.Add(self.btnAddNo,0,wx.ALL,5)
        btnNoSizer.Add(self.btnDelNo,0,wx.ALL,5)

        pointSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5)
        pointSizer.AddMany([
            self.lblPointX0,self.txtPointX0,
            self.lblPointY0,self.txtPointY0,
            self.lblPointX,self.txtPointX,
            self.lblPointY,self.txtPointY,
            self.lblPointColor,self.txtPointColor,
            (0,0),self.btnAnalyse,
            ])

        topSizer = wx.FlexGridSizer(cols=6, hgap=5, vgap=5)
        topSizer.AddMany([self.lblFiles,(0,0),self.lblYes,
            (0,0),self.lblNo,self.lblPoint,
            self.lstFiles,btnYesSizer,self.lstYes,
            btnNoSizer,self.lstNo,pointSizer,
                        ])

        case1Sizer = wx.BoxSizer(wx.HORIZONTAL)
        case1Sizer.Add(self.lblCase1, 0, wx.ALL, 5)
        case1Sizer.Add(self.lblCase1Point, 0, wx.ALL, 5)
        case1Sizer.Add(self.txtCase1Point, 1, wx.ALL | wx.EXPAND, 5)
        case1Sizer.Add(self.btnCase1, 0, wx.ALL, 5)
        case1Sizer.Add(self.lblCase1Result, 0, wx.ALL, 5)
        case1Sizer.Add(self.txtCase1Result, 1, wx.ALL | wx.EXPAND, 5)

        case2Sizer = wx.BoxSizer(wx.HORIZONTAL)
        case2Sizer.Add(self.lblCase2, 0, wx.ALL, 5)
        case2Sizer.Add(self.lblCase2Point, 0, wx.ALL, 5)
        case2Sizer.Add(self.txtCase2Point, 1, wx.ALL | wx.EXPAND, 5)
        case2Sizer.Add(self.lblCase2Color, 0, wx.ALL, 5)
        case2Sizer.Add(self.txtCase2Color, 1, wx.ALL | wx.EXPAND, 5)
        case2Sizer.Add(self.btnCase2, 0, wx.ALL, 5)
        case2Sizer.Add(self.lblCase2Result, 0, wx.ALL, 5)
        case2Sizer.Add(self.txtCase2Result, 1, wx.ALL | wx.EXPAND, 5)

        imgSizer = wx.BoxSizer(wx.VERTICAL)
        imgSizer.Add(self.lblImg,0,wx.ALL,5)
        imgSizer.Add(self.sw,1,wx.ALL | wx.EXPAND,5)

        leftSizer = wx.BoxSizer(wx.VERTICAL)
        leftSizer.Add(topSizer,0,wx.ALL,5)
        leftSizer.Add(case1Sizer,0,wx.ALL,5)
        leftSizer.Add(case2Sizer,0,wx.ALL,5)
        leftSizer.Add(imgSizer,1,wx.ALL | wx.EXPAND,5)
        
        mainSizer = wx.BoxSizer(wx.HORIZONTAL)
        mainSizer.Add(leftSizer, 1, wx.ALL | wx.EXPAND, 5)
         
        self.SetSizer(mainSizer)
        mainSizer.Fit(self)
        mainSizer.SetSizeHints(self)

    def init(self):
        files = os.listdir(self.path)
        self.lstFiles.InsertItems(files,0)

    def __list_add(self,sourceLst,targetLst):
        select_ids = sourceLst.GetSelections()
        for select_id in select_ids:
            select = sourceLst.GetString(select_id)
            targetLst.Append(select)

    def __list_del(lst):
        #TODO:多个条目删除错误
        select_ids = lst.GetSelections()
        for select_id in select_ids:
            lst.Delete(select_id)

    def OnReloadClick(self,evt):
        self.lstFiles.Clear()
        self.lstYes.Clear()
        self.lstNo.Clear()
        self.txtPointX.SetLabel('')
        self.txtPointY.SetLabel('')
        self.txtPointColor.SetLabel('')
        self.init()

    def OnAddYesClick(self,evt):
        self.__list_add(self.lstFiles,self.lstYes)

    def OnDelYesClick(self,evt):
        self.__list_del(self.lstYes)

    def OnAddNoClick(self,evt):
        self.__list_add(self.lstFiles,self.lstNo)

    def OnDelNoClick(self,evt):
        self._list_del(self.lstNo)

    def OnItemClick(self,evt):
        file = r'%s/%s' %(self.path,evt.GetString())
        self.lblImg.SetLabel(file)
        image = wx.Image(file,wx.BITMAP_TYPE_ANY)
        temp = image.ConvertToBitmap()
        self.img.SetBitmap(temp)

    def OnAnalyseClick(self,evt):
        x0 = int(self.txtPointX0.GetLabel())
        y0 = int(self.txtPointY0.GetLabel())
        x = int(self.txtPointX.GetLabel())
        y = int(self.txtPointY.GetLabel())
        color = self.txtPointColor.GetLabel().upper()
        #color not need to define

        yes_error,no_error = [],[]
        for item in self.lstYes.GetItems():
            file = r'%s/%s' %(self.path,item)
            im = Image.open(file)
            decimals = im.getpixel((x0 + x,y0 + y))
            if color != tools.getHexRGBFromDecimal(decimals):
                yes_error.append(item)

        for item in self.lstNo.GetItems():
            file = r'%s/%s' %(self.path,item)
            im = Image.open(file)
            decimals = im.getpixel((x0 + x,y0 + y))
            if color == tools.getHexRGBFromDecimal(decimals):
                no_error.append(item)

        if yes_error or no_error:
            print yes_error
            print no_error
        else:
            print 'good'

    def OnCase1Click(self,evt):
        x0 = int(self.txtPointX0.GetLabel())
        y0 = int(self.txtPointY0.GetLabel())
        x,y = [int(s) for s in self.txtCase1Point.GetLabel().split(',')]

        file = self.lblImg.GetLabel()
        im = Image.open(file)
        decimals = im.getpixel((x0 + x,y0 + y))
        color = tools.getHexRGBFromDecimal(decimals)
        self.txtCase1Result.SetLabel(color)
        
    def OnCase2Click(self,evt):
        x_0 = int(self.txtPointX0.GetLabel())
        y_0 = int(self.txtPointY0.GetLabel())
        x0,y0,x1,y1 = [int(s) for s in self.txtCase2Point.GetLabel().split(',')]
        color = self.txtCase2Color.GetLabel().upper()

        file = self.lblImg.GetLabel()
        im = Image.open(file)
        data = im.getdata()
        width = im.size[0]

        x0 += x_0
        x1 += x_0
        y0 += y_0
        y1 += y_0
        r = ''
        for i in range(x0,x1 + 1):
            for j in range(y0,y1 + 1):
                if tools.checkColor(data[j * width + i],color):
                    r += '(%s,%s),' %(i,j)
        if not r:
            r = 'no'
        self.txtCase2Result.SetLabel(r)


if __name__ == '__main__':
    import config
    log = config.log
    path = r'%s/fetchImg/img' %config.path

    app = wx.App(redirect = False)
    MainFrame(log,path).Show()
    app.MainLoop()
